package com.appkubes.mall.restful.application.customer.customer.service.impl;

import com.appkubes.common.utils.data.string.UUIDUtils;
import com.appkubes.mall.core.entity.MallAdmin;
import com.appkubes.mall.core.entity.MallAdminBinding;
import com.appkubes.mall.core.entity.MallCustomer;
import com.appkubes.mall.core.service.impl.BaseMallCustomerServiceImpl;
import com.appkubes.mall.restful.application.admin.admin.service.AdminService;
import com.appkubes.mall.restful.application.admin.binding.service.AdminBindingService;
import com.appkubes.mall.restful.application.customer.customer.entity.dto.CustomerInfoDTO;
import com.appkubes.mall.restful.application.customer.customer.service.CustomerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: Rongjie
 * @Date: 2020/2/27
 * @Description:
 */
@Service
public class CustomerServiceImpl extends BaseMallCustomerServiceImpl implements CustomerService {

    @Autowired
    AdminService adminService;

    @Autowired
    AdminBindingService adminBindingService;

    public String adminKeyGetCustomerKey(String adminKey){
        MallAdmin admin = new MallAdmin();
        admin.setAdminKey(adminKey);
        if(adminService.getOneByEntity(admin) == null){
            adminService.save(admin);
        }

        MallAdminBinding adminBinding = new MallAdminBinding();
        adminBinding.setAdminKey(adminKey);
        MallAdminBinding adminBindingRes = adminBindingService.getOneByEntity(adminBinding);
        if(adminBindingRes == null){
            String customerKey = UUIDUtils.getUUID();

            adminBinding.setCustomerKey(customerKey);
            adminBindingService.save(adminBinding);
            return customerKey;
        }else if(adminBindingRes.getCustomerKey().equals("")){
            String customerKey = UUIDUtils.getUUID();
            adminBinding.setCustomerKey(customerKey);
            adminBindingService.updateById(adminBinding);
            return customerKey;
        }else{
            return adminBindingRes.getCustomerKey();
        }
    }

    @Override
    public CustomerInfoDTO getCustomerInfo(String adminKey) {
        String customerKey = adminKeyGetCustomerKey(adminKey);

        MallCustomer customer = new MallCustomer();
        customer.setCustomerKey(customerKey);
        MallCustomer customerRes = this.getOneByEntity(customer);
        CustomerInfoDTO customerInfoDTO = new CustomerInfoDTO();
        if(customerRes == null){
            this.save(customer);
            BeanUtils.copyProperties(customer,customerInfoDTO);
        }else{
            BeanUtils.copyProperties(customerRes,customerInfoDTO);
        }
        return customerInfoDTO;
    }
}
